package com.csu.geo.service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Query;

import org.hibernate.SQLQuery;
import org.hibernate.transform.Transformers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.csu.geo.entity.Log;
import com.csu.geo.repository.LogDao;

@Component
@Transactional
public class LogService {
	@Autowired
	private LogDao logDao;
	@Autowired
	private  EntityManagerFactory entityManagerFactory;
	
	public String saveLog(Log log)
	{
		if(logDao.save(log)!=null)
		{
			return "0000";
		}
		else {
			return "0001";
		}
	}
    
	public List<Log> getAllLog()
	{
		return logDao.getAllLog();
	}
	
	public  Map<String , Integer> getAdminCheckCount(String name)
	{
		String queryStr="SELECT type ,count(type) FROM log  WHERE adminname='"+name+"' group by type";
		EntityManager entityManager=entityManagerFactory.createEntityManager();
		Query query=entityManager.createNativeQuery(queryStr);
		 query.unwrap(SQLQuery.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
		 @SuppressWarnings("rawtypes")
		List list=query.getResultList();
		 Map<String, Integer> result=new HashMap<>();
		 for(Object object:list)
		 {
			 @SuppressWarnings("rawtypes")
			Map row=(Map) object;
			 result.put(row.get("type").toString(),Integer.parseInt(row.get("count").toString()));
		 }
		 if(!result.containsKey("Point"))
		 {
			 result.put("Point", 0);
		 }
		 if(!result.containsKey("Line"))
		 {
			 result.put("Line", 0);
		 }
		 if(!result.containsKey("Polygon"))
		 {
			 result.put("Polygon", 0);
		 }
		 Integer sum=result.get("Point")+result.get("Line")+result.get("Polygon");
		 result.put("sum", sum);
		 entityManager.close();
		 return result;
	}
	
}
